package com.garmin.tw.garminpcsync.android;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.conn.HttpHostConnectException;
import org.xmlrpc.android.XMLRPCClient;
import org.xmlrpc.android.XMLRPCException;
import org.xmlrpc.android.XMLRPCFault;
import org.xmlrpc.android.XMLRPCSerializable;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextSwitcher;
import android.widget.TextView;

import com.garmin.tw.garminpcsync.android.sessions.SessionManager;
import com.garmin.tw.garminpcsync.android.utils.Constants;
import com.garmin.tw.garminpcsync.common.domain.xmlrpc.MapUpdateInfo;
import com.garmin.tw.garminpcsync.common.domain.xmlrpc.PreloadMapUpdateResult;
import com.garmin.tw.garminpcsync.common.domain.xmlrpc.SoftwareUpdateInfo;
import com.garmin.tw.garminpcsync.common.domain.xmlrpc.UpdateAvailabilityResult;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.Tracker;

/**
 * Demonstrates use of XMLRPC library.
 * 
 * What you really need to do is:
 * <ul>
 * <li>create XMLRPCClient client
 * 
 * <pre>
 * XMLRPCClient client = new XMLRPCClient(URI.create(&quot;http://10.0.2.2:8888&quot;));
 * </pre>
 * 
 * or even
 * 
 * <pre>
 * XMLRPCClient client = new XMLRPCClient(&quot;http://10.0.2.2:8888&quot;);
 * </pre>
 * 
 * </li>
 * <li>call RPCXML method
 * 
 * <pre>
 * try {
 * 	// call method &quot;add&quot; with two parameters: 2 and 4
 * 	int i = (Integer) client.call(&quot;add&quot;, 2, 4);
 * 	Log.d(&quot;XMLRPC Test&quot;, &quot;result int i = &quot; + i);
 * } catch (XMLRPCException e) {
 * 	Log.d(&quot;XMLRPC Test&quot;, &quot;Error&quot;, e);
 * }
 * </pre>
 * 
 * </li>
 * </ul>
 * 
 */

public class MainEntry extends Activity {

	private XMLRPCClient client;

	// "http://testmy.garmin.com.tw/GarminPCSync/xmlrpc";
	// getString(R.string.server_url);
	private String uriStr = Constants.SERVER_URI;

	private URI uri;
	private DateFormat dateFormat;
	private DateFormat timeFormat;
	private Drawable errorDrawable;

	private TextView status;
	private TextSwitcher testResult;
	private ListView tests;

	private ProgressDialog progressDialog;

	private SessionManager sessionManager;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		uri = URI.create(this.uriStr);
		client = new XMLRPCClient(uri);

		sessionManager = new SessionManager(this.getApplicationContext());

		setContentView(R.layout.main);
		testResult = (TextSwitcher) findViewById(R.id.text_result);

		LayoutInflater inflater = LayoutInflater.from(this);
		View v0 = inflater.inflate(R.layout.text_view, null);
		View v1 = inflater.inflate(R.layout.text_view, null);
		LayoutParams layoutParams = new ViewGroup.LayoutParams(
				ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.MATCH_PARENT);
		testResult.addView(v0, 0, layoutParams);
		testResult.addView(v1, 1, layoutParams);
		testResult
				.setText("WARNING, before calling any test make sure GarminPCSync is reachable !!!");

		Animation inAnim = AnimationUtils.loadAnimation(this,
				R.anim.push_left_in);
		Animation outAnim = AnimationUtils.loadAnimation(this,
				R.anim.push_left_out);
		// Animation inAnim = AnimationUtils.loadAnimation(this,
		// android.R.anim.fade_in);
		// Animation outAnim = AnimationUtils.loadAnimation(this,
		// android.R.anim.fade_out);
		inAnim.setStartOffset(250);
		testResult.setInAnimation(inAnim);
		testResult.setOutAnimation(outAnim);
		errorDrawable = getResources().getDrawable(R.drawable.error);
		errorDrawable.setBounds(0, 0, errorDrawable.getIntrinsicWidth(),
				errorDrawable.getIntrinsicHeight());

		status = (TextView) findViewById(R.id.status);
		dateFormat = SimpleDateFormat.getDateInstance(SimpleDateFormat.FULL);
		timeFormat = SimpleDateFormat.getTimeInstance(SimpleDateFormat.DEFAULT);

		tests = (ListView) findViewById(R.id.tests);
		ArrayAdapter<String> adapter = new TestAdapter(this, R.layout.test,
				R.id.title);

		adapter.add("add 2 to 3; in [int, int] out int");
		adapter.add("auth; in [userId, password, esn] out Object");
		adapter.add("checkUpdateAvailabilityByDeviceXML;");
		adapter.add("deviceRegister; in [...] out Object");
		adapter.add("forgotUserName; in [String] out void");
		adapter.add("forgotPassword; in [String, String] out void");
		adapter.add("registerUser; in [String, String, String] out Object");
		adapter.add("unlockPreloadMapUpdate; in [userId, password, esn] out Object");
		adapter.add("getGPIList; in [esn] out Object");
		adapter.add("getGarageList; in [esn] out Object");
		adapter.add("getTravelRouteList; in [esn] out Object");
		adapter.add("getNewsList; in [esn] out Object");

		tests.setAdapter(adapter);
		tests.setOnItemClickListener(testListener);

		progressDialog = new ProgressDialog(this);
		progressDialog.setMessage("Loading. Please wait...");
	}

	OnItemClickListener testListener = new OnItemClickListener() {
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {

			// Get current context.
			Context mCtx = MainEntry.this;
			// setContext will use mCtx to retrieve the application context.
			EasyTracker.getInstance().setContext(mCtx);
			// EasyTracker is now ready for use.
			Tracker myTracker = EasyTracker.getTracker();

			// Add
			if (position == 0) {
				LayoutInflater inflater = LayoutInflater.from(MainEntry.this);
				final View add_view = inflater.inflate(R.layout.add, null);

				EditText editText1 = (EditText) add_view
						.findViewById(R.id.editText1);
				editText1.setText("2");

				EditText editText2 = (EditText) add_view
						.findViewById(R.id.editText2);
				editText2.setText("3");

				new AlertDialog.Builder(MainEntry.this)
						.setTitle("Add")
						.setView(add_view)
						.setPositiveButton("Ok",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
										EditText editText1 = (EditText) add_view
												.findViewById(R.id.editText1);
										EditText editText2 = (EditText) add_view
												.findViewById(R.id.editText2);

										dialog.cancel();

										MainEntry.this
												.runOnUiThread(new Runnable() {
													@Override
													public void run() {
														MainEntry.this.progressDialog
																.show();
													}
												});

										XMLRPCMethod method = new XMLRPCMethod(
												"APIDispatcher.add",
												new XMLRPCMethodCallback() {
													public void callFinished(
															Object result) {
														testResult.setText("Sum is "
																+ result.toString());
														progressDialog.cancel();
													}
												});
										Object[] params = {
												Integer.parseInt(editText1
														.getText().toString()),
												Integer.parseInt(editText2
														.getText().toString()) };
										method.call(params);
									}
								})
						.setNegativeButton("Cancel",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
										// Do nothing.
										dialog.cancel();
									}
								}).show();
			}
			// Auth
			else if (position == 1) {

			}
			// CheckUpdateAvailabilityByDeviceXML
			else if (position == 2) {

				myTracker.trackEvent("Main Page", "Check Software Upgrade",
						null, null);

				MainEntry.this.runOnUiThread(new Runnable() {
					@Override
					public void run() {
						progressDialog.show();
					}
				});

				XMLRPCMethod method = new XMLRPCMethod(
						"APIDispatcher.checkUpdateAvailabilityByDeviceXML",
						new XMLRPCMethodCallback() {
							public void callFinished(Object result) {
								progressDialog.cancel();

								if (result instanceof UpdateAvailabilityResult) {
									UpdateAvailabilityResult updateAvailabilityResult = (UpdateAvailabilityResult) result;

									List<String> skuList = new ArrayList<String>();
									List<String> versionList = new ArrayList<String>();
									List<String> downloadUrlList = new ArrayList<String>();

									// sb.append("\n");
									// sb.append("SoftwareUpdateInfoList.size()="
									// +
									// updateAvailabilityResult.getSoftwareUpdateInfoList().size());
									// sb.append("\n");
									for (int index = 0; index < updateAvailabilityResult
											.getSoftwareUpdateInfoList().size(); index++) {
										SoftwareUpdateInfo softwareUpdateInfo = updateAvailabilityResult
												.getSoftwareUpdateInfoList()
												.get(index);

										if (softwareUpdateInfo
												.getUpdateAvailable()
												.booleanValue()) {

											skuList.add(softwareUpdateInfo
													.getLatestSku());
											versionList.add(softwareUpdateInfo
													.getOriginalVersion()
													+ " -> "
													+ softwareUpdateInfo
															.getLatestVersion());
											downloadUrlList.add(softwareUpdateInfo
													.getServerPath()
													+ softwareUpdateInfo
															.getFileName());
										}
									}
									// sb.append("MapUpdateInfoList.size()=" +
									// ((updateAvailabilityResult.getMapUpdateInfoList()
									// ==
									// null)?"0":updateAvailabilityResult.getMapUpdateInfoList().size()));
									for (int index = 0; index < updateAvailabilityResult
											.getMapUpdateInfoList().size(); index++) {
										MapUpdateInfo mapUpdateInfo = updateAvailabilityResult
												.getMapUpdateInfoList().get(
														index);

										if (mapUpdateInfo.getUpdateAvailable()
												.booleanValue()) {
											skuList.add(mapUpdateInfo
													.getLatestSku());
											versionList.add(mapUpdateInfo
													.getOriginalVersion()
													+ " -> "
													+ mapUpdateInfo
															.getLatestVersion());
											downloadUrlList.add(mapUpdateInfo
													.getServerPath()
													+ mapUpdateInfo
															.getFileName());
										}
									}

									testResult
											.setText("ReturnCode="
													+ updateAvailabilityResult
															.getReturnCode()
															.toString());

									String[] array1 = (String[]) skuList
											.toArray(new String[0]);
									String[] array2 = (String[]) versionList
											.toArray(new String[0]);
									String[] array3 = (String[]) downloadUrlList
											.toArray(new String[0]);

									final Intent updateListIntent = new Intent(
											MainEntry.this
													.getApplicationContext(),
											UpgradeFilesListViewActivity.class);
									updateListIntent
											.putExtra("skuList", array1);
									updateListIntent.putExtra("versionList",
											array2);
									updateListIntent.putExtra(
											"downloadUrlList", array3);

									startActivityForResult(updateListIntent, 0);
								}
							}
						});
				/*
				 * base64Str
				 */
				// GarminDevice gd = new GarminDevice();
				// Object[] params = { gd.getBASE64Str() };
				StringBuilder sb = new StringBuilder();
				try {
					File file = new File("/mnt/sdcard/Garmin/GarminDevice.xml");
					FileInputStream in = new FileInputStream(file);// openFileInput("GarminDevice.xml");
					InputStreamReader inputStreamReader = new InputStreamReader(
							in);
					BufferedReader bufferedReader = new BufferedReader(
							inputStreamReader);

					String line;
					while ((line = bufferedReader.readLine()) != null) {
						sb.append(line);
					}
				} catch (FileNotFoundException e1) {
					e1.printStackTrace();
					progressDialog.cancel();
				} catch (IOException e2) {
					e2.printStackTrace();
					progressDialog.cancel();
				}

				if (sb.length() > 0) {
					byte[] data;
					try {
						data = sb.toString().getBytes("UTF-8");
						String base64 = Base64.encodeToString(data,
								Base64.DEFAULT);

						Object[] params = { base64 };
						method.call(params);
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
						progressDialog.cancel();
					}
				} else {
					progressDialog.cancel();
				}
			}
			// Device Register
			else if (position == 3) {

				LayoutInflater inflater = LayoutInflater.from(MainEntry.this);
				final View auth_view = inflater.inflate(R.layout.device, null);

				EditText editText1 = (EditText) auth_view
						.findViewById(R.id.editText1);
				editText1.setText("here.hsieh");
				EditText editText2 = (EditText) auth_view
						.findViewById(R.id.editText2);
				editText2.setText("123456");
				EditText editText3 = (EditText) auth_view
						.findViewById(R.id.editText3);
				editText3.setText("3394320185");

				new AlertDialog.Builder(MainEntry.this)
						.setTitle("Device Register")
						.setView(auth_view)
						.setPositiveButton("Ok",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
										EditText editText1 = (EditText) auth_view
												.findViewById(R.id.editText1);
										EditText editText2 = (EditText) auth_view
												.findViewById(R.id.editText2);
										EditText editText3 = (EditText) auth_view
												.findViewById(R.id.editText3);

										dialog.cancel();

										MainEntry.this
												.runOnUiThread(new Runnable() {
													@Override
													public void run() {
														progressDialog.show();
													}
												});

										XMLRPCMethod method = new XMLRPCMethod(
												"APIDispatcher.deviceRegister",
												new XMLRPCMethodCallback() {
													public void callFinished(
															Object result) {
														if (result instanceof Integer) {
															testResult.setText("ReturnCode="
																	+ result.toString());
														}
													}
												});
										Object[] params = {
												editText1.getText().toString(),
												editText2.getText().toString(),
												editText3.getText().toString() };
										method.call(params);
									}
								})
						.setNegativeButton("Cancel",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
										// Do nothing.
										dialog.cancel();
									}
								}).show();

				// Forgot User Name
			} else if (position == 4) {

				myTracker.trackEvent("Login Page", "Click Forgot UserName",
						null, null);

				LayoutInflater inflater = LayoutInflater.from(MainEntry.this);
				final View forgotuser_view = inflater.inflate(
						R.layout.forgotuser, null);

				EditText editText1 = (EditText) forgotuser_view
						.findViewById(R.id.editText1);
				editText1.setText("here.hsieh@garmin.com");

				new AlertDialog.Builder(MainEntry.this)
						.setTitle("Forgot User Name")
						.setView(forgotuser_view)
						.setPositiveButton("Ok",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										EditText editText1 = (EditText) forgotuser_view
												.findViewById(R.id.editText1);

										dialog.cancel();

										MainEntry.this
												.runOnUiThread(new Runnable() {
													@Override
													public void run() {
														progressDialog.show();
													}
												});

										XMLRPCMethod method = new XMLRPCMethod(
												"APIDispatcher.forgotUserName",
												new XMLRPCMethodCallback() {
													public void callFinished(
															Object result) {
														if (result instanceof Integer) {
															testResult.setText("ReturnCode="
																	+ result.toString());
														}
														progressDialog.cancel();
													}
												});
										Object[] params = { editText1.getText()
												.toString() };
										method.call(params);
									}

								})
						.setNegativeButton("Cancel",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
										// Do nothing.
										dialog.cancel();
									}
								}).show();
				//Forgot Password
			} else if (position == 5) {

				myTracker.trackEvent("Login Page", "Click Forgot Password",
						null, null);

				LayoutInflater inflater = LayoutInflater.from(MainEntry.this);
				final View forgotpwd_view = inflater.inflate(
						R.layout.forgotpwd, null);

				new AlertDialog.Builder(MainEntry.this)
						.setTitle("Forgot Password")
						.setView(forgotpwd_view)
						.setPositiveButton("Ok",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										EditText editText1 = (EditText) forgotpwd_view
												.findViewById(R.id.editText1);
										EditText editText2 = (EditText) forgotpwd_view
												.findViewById(R.id.editText2);

										dialog.cancel();

										MainEntry.this
												.runOnUiThread(new Runnable() {
													@Override
													public void run() {
														progressDialog.show();
													}
												});

										XMLRPCMethod method = new XMLRPCMethod(
												"APIDispatcher.forgotPassword",
												new XMLRPCMethodCallback() {
													public void callFinished(
															Object result) {
														if (result instanceof Integer) {
															testResult.setText("ReturnCode="
																	+ result.toString());
														}
														progressDialog.cancel();
													}
												});
										Object[] params = {
												editText1.getText().toString(),
												editText2.getText().toString() };
										method.call(params);
									}

								})
						.setNegativeButton("Cancel",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
										// Do nothing.
										dialog.cancel();
									}
								}).show();

			} else if (position == 6) {

				myTracker.trackEvent("Login Page", "Click Create Account",
						null, null);

				LayoutInflater inflater = LayoutInflater.from(MainEntry.this);
				final View register_view = inflater.inflate(R.layout.register,
						null);

				new AlertDialog.Builder(MainEntry.this)
						.setTitle("Register User")
						.setView(register_view)
						.setPositiveButton("Ok",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
										EditText editText1 = (EditText) register_view
												.findViewById(R.id.editText1);
										EditText editText2 = (EditText) register_view
												.findViewById(R.id.editText2);
										EditText editText3 = (EditText) register_view
												.findViewById(R.id.editText3);
										EditText editText4 = (EditText) register_view
												.findViewById(R.id.editText4);

										if (!editText2
												.getText()
												.toString()
												.equals(editText3.getText()
														.toString())) {
											return;
										}

										MainEntry.this
												.runOnUiThread(new Runnable() {
													@Override
													public void run() {
														progressDialog.show();
													}
												});

										dialog.cancel();

										XMLRPCMethod method = new XMLRPCMethod(
												"APIDispatcher.registerUser",
												new XMLRPCMethodCallback() {
													public void callFinished(
															Object result) {
														if (result instanceof Integer) {
															testResult.setText("ReturnCode="
																	+ result.toString());
														}
														progressDialog.cancel();
													}
												});
										/*
										 * userId password esn
										 */
										Object[] params = {
												editText1.getText().toString(),
												editText2.getText().toString(),
												editText4.getText().toString() };
										method.call(params);
									}
								})
						.setNegativeButton("Cancel",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
										// Do nothing.
										dialog.cancel();
									}
								}).show();
				//UnlockPreloadMap
			} else if (position == 7) {
				LayoutInflater inflater = LayoutInflater.from(MainEntry.this);
				final View unlock_view = inflater
						.inflate(R.layout.unlock, null);

				EditText editText1 = (EditText) unlock_view
						.findViewById(R.id.editText1);
				EditText editText2 = (EditText) unlock_view
						.findViewById(R.id.editText2);
				EditText editText3 = (EditText) unlock_view
						.findViewById(R.id.editText3);

				if (sessionManager != null && sessionManager.getUserDetails() != null) {
					HashMap<String, String> userDetails = sessionManager.getUserDetails();
					editText1.setText(userDetails.get(SessionManager.KEY_USERNAME));
					editText2.setText(userDetails.get(SessionManager.KEY_PASSWORD));
					editText3.setText(userDetails.get(SessionManager.KEY_ESN));
				}

				new AlertDialog.Builder(MainEntry.this)
						.setTitle("Unlock Preload Map Update")
						.setView(unlock_view)
						.setPositiveButton("Ok",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
										EditText editText1 = (EditText) unlock_view
												.findViewById(R.id.editText1);
										EditText editText2 = (EditText) unlock_view
												.findViewById(R.id.editText2);
										EditText editText3 = (EditText) unlock_view
												.findViewById(R.id.editText3);

										MainEntry.this
												.runOnUiThread(new Runnable() {
													@Override
													public void run() {
														progressDialog.show();
													}
												});

										dialog.cancel();

										XMLRPCMethod method = new XMLRPCMethod(
												"APIDispatcher.unlockPreloadMapUpdate",
												new XMLRPCMethodCallback() {
													public void callFinished(
															Object result) {
														if (result instanceof PreloadMapUpdateResult) {
															PreloadMapUpdateResult preloadMapUpdateResult = (PreloadMapUpdateResult) result;

															testResult.setText("UnlockCode="
																	+ preloadMapUpdateResult
																			.getUnlockCode());
														}
														progressDialog.cancel();
													}
												});
										/*
										 * userId password esn
										 */
										Object[] params = {
												editText1.getText().toString(),
												editText2.getText().toString(),
												editText3.getText().toString() };
										method.call(params);
									}
								})
						.setNegativeButton("Cancel",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
										// Do nothing.
										dialog.cancel();
									}
								}).show();

			} else if (position == 8) {

				myTracker.trackEvent("Main Page", "Get RichPOI List",
						"RichPoi", null);

				final Intent showResultIntent = new Intent(
						MainEntry.this.getApplicationContext(),
						RichPoiListViewActivity.class);
				startActivityForResult(showResultIntent, 0);
			} else if (position == 9) {
				myTracker.trackEvent("Main Page", "Get Garage List", "Garage",
						null);

				/*
				 * Test.this.runOnUiThread(new Runnable() {
				 * 
				 * @Override public void run() { progressDialog.show(); } });
				 */

				final Intent showResultIntent = new Intent(
						MainEntry.this.getApplicationContext(),
						GarageListViewActivity.class);
				// showResultIntent.putExtra("description", array1);
				// showResultIntent.putExtra("fileSize", array2);
				// showResultIntent.putExtra("thumbnailUrl", array3);
				// showResultIntent.putExtra("downloadUrlList", array4);

				startActivityForResult(showResultIntent, 0);
			} else if (position == 10) {

				myTracker.trackEvent("Main Page", "Get TravelRoute List",
						"TravelRoute", null);

				final Intent showResultIntent = new Intent(
						MainEntry.this.getApplicationContext(),
						TravelRouteListViewActivity.class);

				startActivityForResult(showResultIntent, 0);

			} else if (position == 11) {

				myTracker.trackEvent("Main Page", "Get myGarmin Message List",
						"myGarmin Message", null);

				final Intent showResultIntent = new Intent(
						MainEntry.this.getApplicationContext(),
						NewsListViewActivity.class);
				startActivityForResult(showResultIntent, 0);
			}
		}
	};

	class Person implements XMLRPCSerializable {
		private String firstName;
		private String lastName;

		public Person(String firstName, String lastName) {
			this.firstName = firstName;
			this.lastName = lastName;
		}

		public Object getSerializable() {
			Map<String, String> map = new HashMap<String, String>();
			map.put("firstName", firstName);
			map.put("lastName", lastName);
			return map;
		}
	}

	class TestAdapter extends ArrayAdapter<String> {
		private LayoutInflater layouter;
		private int layoutId;

		public TestAdapter(Context context, int layoutId, int textId) {
			super(context, layoutId, textId);
			this.layoutId = layoutId;
			layouter = LayoutInflater.from(MainEntry.this);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = layouter.inflate(layoutId, null);
			TextView title = (TextView) view.findViewById(R.id.title);
			TextView params = (TextView) view.findViewById(R.id.params);
			String string = getItem(position);
			String[] arr = string.split(";");
			title.setText(arr[0]);
			if (arr.length == 2) {
				params.setText(arr[1]);
			} else {
				params.setVisibility(View.GONE);
			}
			return view;
		}
	}

	public interface XMLRPCMethodCallback {
		void callFinished(Object result);
	}

	public class XMLRPCMethod extends Thread {
		private String method;
		private Object[] params;
		private Handler handler;
		private XMLRPCMethodCallback callBack;

		public XMLRPCMethod(String method, XMLRPCMethodCallback callBack) {
			this.method = method;
			this.callBack = callBack;
			handler = new Handler();
		}

		public void call() {
			call(null);
		}

		public void call(Object[] params) {
			status.setTextColor(0xff80ff80);
			status.setError(null);
			status.setText("Calling host: " + uri.getHost()
					+ ((uri.getPort() == -1) ? "" : ":" + uri.getPort()));
			tests.setEnabled(false);
			this.params = params;
			start();
		}

		@Override
		public void run() {
			try {
				final long t0 = System.currentTimeMillis();
				final Object result = client.callEx(method, params);
				final long t1 = System.currentTimeMillis();
				handler.post(new Runnable() {
					public void run() {
						tests.setEnabled(true);
						status.setText("XML-RPC call took " + (t1 - t0) + "ms");
						callBack.callFinished(result);
					}
				});
			} catch (final XMLRPCFault e) {
				handler.post(new Runnable() {
					public void run() {
						testResult.setText("");
						tests.setEnabled(true);
						status.setTextColor(0xffff8080);
						status.setError("", errorDrawable);
						status.setText("Fault message: " + e.getFaultString()
								+ "\nFault code: " + e.getFaultCode());
						Log.d("Test", "error", e);
					}
				});
			} catch (final XMLRPCException e) {
				handler.post(new Runnable() {
					public void run() {
						testResult.setText("");
						tests.setEnabled(true);
						status.setTextColor(0xffff8080);
						status.setError("", errorDrawable);
						Throwable couse = e.getCause();
						if (couse instanceof HttpHostConnectException) {
							status.setText("Cannot connect to "
									+ uri.getHost()
									+ ":"
									+ uri.getPort()
									+ "\nMake sure GarminPCSync on your development host is running !!!");
						} else {
							status.setText("Error " + e.getMessage());
						}
						Log.d("Test", "error", e);
					}
				});
			} finally {
				// Cancel Progress Dialog
				progressDialog.cancel();
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// 參數1:群組id, 參數2:itemId, 參數3:item順序, 參數4:item名稱
		/*
		 * menu.add(0, 0, 0, "Setting"); menu.add(0, 1, 1, "Exit"); return
		 * super.onCreateOptionsMenu(menu);
		 */

		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_activity, menu);

		MenuItem loginMenuItem = menu.findItem(R.id.menu_login);
		if (sessionManager.isLoggedIn()) {
			loginMenuItem.setIcon(R.drawable.ic_menu_logout);
		} else {
			loginMenuItem.setIcon(R.drawable.ic_menu_login);
		}

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		final MenuItem f_item = item;
		// 依據itemId來判斷使用者點選哪一個item
		switch (item.getItemId()) {
		case R.id.menu_login:
			if (sessionManager.isLoggedIn()) {
				sessionManager.logoutUser();
				this.invalidateOptionsMenu();
				this.runOnUiThread(new Runnable() {

					@Override
					public void run() {
						f_item.setIcon(R.drawable.ic_menu_login);
					}

				});
			} else {
				Intent intent = new Intent(MainEntry.this, LoginActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
			}
			break;
		case R.id.menu_settings:

			LayoutInflater inflater = LayoutInflater.from(this);
			final View setting_view = inflater.inflate(R.layout.setting, null);

			EditText editText1 = (EditText) setting_view
					.findViewById(R.id.editText1);
			editText1.setText(MainEntry.this.uriStr);

			new AlertDialog.Builder(this)
					.setTitle("Setting")
					// .setMessage("Server URL:")
					.setView(setting_view)
					.setPositiveButton("Ok",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									EditText editText1 = (EditText) setting_view
											.findViewById(R.id.editText1);

									MainEntry.this.uriStr = editText1.getText()
											.toString();
									MainEntry.this.uri = URI.create(editText1
											.getText().toString());
									MainEntry.this.client = new XMLRPCClient(
											MainEntry.this.uri);
								}
							})
					.setNegativeButton("Cancel",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									// Do nothing.
								}
							}).show();

			/*
			 * this.runOnUiThread(new Runnable() {
			 * 
			 * @Override public void run() { EditText editText1 =
			 * (EditText)input_view.findViewById(R.id.editText1);
			 * editText1.setText(Test.this.uriStr); }
			 * 
			 * });
			 */

			break;
		case R.id.menu_exit:
			// 結束此程式
			new AlertDialog.Builder(this)
					// .setIcon(android.R.drawable.ic_dialog_alert)
					.setTitle("Exit Application")
					.setMessage("Are you sure you would like to exit the App?")
					.setPositiveButton("OK",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// Stop the activity
									MainEntry.this.finish();
								}

							}).setNegativeButton("Cancel", null).show();
			break;
		default:
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// Handle the back button
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			new AlertDialog.Builder(this)
					// .setIcon(android.R.drawable.ic_dialog_alert)
					.setTitle("Exit Application")
					.setMessage("Are you sure you would like to exit the App?")
					.setPositiveButton("OK",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// Stop the activity
									MainEntry.this.finish();
								}

							}).setNegativeButton("Cancel", null).show();

			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	@Override
	public void onStart() {
		super.onStart();
		// ... // The rest of your onStart() code.
		EasyTracker.getInstance().activityStart(this); // Add this method.
	}

	@Override
	public void onStop() {
		super.onStop();
		// ... // The rest of your onStop() code.
		EasyTracker.getInstance().activityStop(this); // Add this method.
	}
}
